#include <io.h>
#include <iostream>
#include <fstream>

#include "file.h"

mztool::File::File(String path)
{
    this->m_path = path;
}

mztool::File::File(std::string path)
{
    this->m_path = String(path);
}

bool mztool::File::IsDirectory()
{
    return this->m_fileType == mztool::FileType::DIRECTORY;
}

bool mztool::File::Exists()
{
    std::fstream file(m_path.ToString());
    return file.good();
}

std::vector<mztool::String> mztool::File::ListChildFiles(mztool::FileType type)
{
    // c++ 17 可使用filesystem模块获取
    std::vector<mztool::String> childFiles;
    std::string dir = m_path.ToString();

#ifdef WIN32
    long hFile = 0;
    struct _finddata_t fileInfo;
    std::string path = dir;
    if ((hFile = _findfirst(path.append("\\*").c_str(), &fileInfo)) == -1){
        return childFiles;
    }
    do {
        bool need = ((fileInfo.attrib & _A_SUBDIR) && ((int)type & (int)mztool::FileType::DIRECTORY)) ||
            ((fileInfo.attrib & _A_ARCH) && ((int)type & (int)mztool::FileType::FILE));
        if (!need){
            continue;
        }
        path = dir;
        childFiles.emplace_back(String(path.append("\\").append(fileInfo.name)));
    } while (_findnext(hFile, &fileInfo) == 0);
    _findclose(hFile);
#else
    // other 环境
#endif

    return childFiles;
}
